from rest_framework import serializers
from  rest_framework.serializers import ModelSerializer

from work.models import Label, Topic


class LabelSerializer(ModelSerializer):
    username = serializers.CharField(source='user.username', read_only=True)  # 优化

    class Meta:
        model = Label
        fields = '__all__'

        extra_kwargs = {  # 对已有字段优化
            'user': {'write_only': True}
        }


class TopicSerializer(ModelSerializer):
    label_name = serializers.CharField(source='label.name', read_only=True)
    username = serializers.CharField(source='user.username', read_only=True)

    class Meta:
        model = Topic
        exclude = ['is_delete']
        extra_kwargs = {
            'label': {'write_only': True},
            'user': {'write_only': True}
        }


class TopicNoAnswerSerializer(ModelSerializer):
    label_name = serializers.CharField(source='label.name', read_only=True)
    username = serializers.CharField(source='user.username', read_only=True)

    class Meta:
        model = Topic
        exclude = ['is_delete', 'answer']
        extra_kwargs = {
            'label': {'write_only': True},
            'user': {'write_only': True}
        }


# 阶段考核，即选择指定的某个标签下所有题目
class LabelTopicSerializer(ModelSerializer):
    # 从题目下的label标签查看他的标签，反向操作：模型小写_set
    topic_set = TopicNoAnswerSerializer(many=True, required=False, read_only=True)

    class Meta:
        model = Label
        fields = '__all__'
